import { UserProps } from "type/user";
import { ResponseProps } from "type/http";
import { UserFromProps } from "type/user";
import { API_URL } from "utils/http";

const localStorageKey: string = "__auth_provider_token__";

export const getToken = () => window.localStorage.getItem(localStorageKey);

export const handleUserResponse = ({ user }: { user: UserProps }) => {
  window.localStorage.setItem(localStorageKey, user.token || "");
  return user;
};

export const login = (params: UserFromProps) => {
  return fetch(`${API_URL}/login`, {
    method: "post",
    headers: { "Content-Type": "application/json;charset=utf-8;" },
    body: JSON.stringify(params),
  }).then(async (res) => {
    const resJson = (await res.json()) as ResponseProps;
    if (res.ok) {
      handleUserResponse({ user: resJson.data });
      return resJson;
    } else {
      return Promise.reject(resJson);
    }
  });
};

export const register = (params: UserFromProps) => {
  return fetch(`${API_URL}/register`, {
    method: "post",
    headers: { "Content-Type": "application/json;charset=utf-8;" },
    body: JSON.stringify(params),
  }).then(async (res) => {
    if (res.ok) {
      return (await res.json()) as ResponseProps;
    } else {
      return Promise.reject(res);
    }
  });
};

export const logout = async () =>
  window.localStorage.removeItem(localStorageKey);
